package com.ruoyi.quartz.task;

import com.ruoyi.quartz.domain.SysSpiderArticle;
import com.ruoyi.quartz.domain.SysSpiderArticleStepConrent;
import com.ruoyi.quartz.domain.SysSpiderArticleUrl;
import com.ruoyi.quartz.service.ISysSpiderArticleService;
import com.ruoyi.quartz.service.ISysSpiderArticleStepConrentService;
import com.ruoyi.quartz.service.ISysSpiderArticleUrlService;
import com.tencent.SpeechClient;
import com.tencent.core.model.GlobalConfig;
import com.tencent.tts.model.SpeechSynthesisRequest;
import com.tencent.tts.model.SpeechSynthesisResponse;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.service.SpeechSynthesizer;
import com.tencent.tts.utils.Ttsutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ArticleTask")
@Slf4j
public class ArticleTask {

    //爬取文章脚本地址
    @Value("${pythonConfig.articleUrl}")
    private String articleUrl;

    //爬取文章信息脚本地址
    @Value("${pythonConfig.articleInfoUrl}")
    private String articleInfoUrl;

    //语音转视频
    @Value("${pythonConfig.articleAudioToVideo}")
    private String articleAudioToVideo;

    //多个视频合并
    @Value("${pythonConfig.articleVideoMerge}")
    private String articleVideoMerge;

    private static String codec = "pcm";
    // 智美	客服女声
    private static Integer type = 1003;
    private static int sampleRate = 16000;
    // 文件保存位置
    private static String save_path = "./audio/";

    @Autowired
    private ISysSpiderArticleUrlService sysSpiderArticleUrlService;

    @Autowired
    private ISysSpiderArticleService sysSpiderArticleService;

    @Autowired
    private ISysSpiderArticleStepConrentService stepConrentService;


    //获取文章信息
    public void getArticle(){
        try {
            SysSpiderArticleUrl url = new SysSpiderArticleUrl();
            url.setState("0");
            List<SysSpiderArticleUrl> list = sysSpiderArticleUrlService.selectSysSpiderArticleUrlList(url);
            //调用python
            if(list != null && list.size() > 0){
                log.info("获取文章开始url:"+list.get(0).getUrl());
                toPython(articleInfoUrl,list.get(0).getUrl());
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    //获取文章基本信息
    public void getArticleInfo(){
        try {
            SysSpiderArticleUrl url = new SysSpiderArticleUrl();
            url.setState("1");
            List<SysSpiderArticleUrl> list = sysSpiderArticleUrlService.selectSysSpiderArticleUrlList(url);
            //调用python
            if(list != null && list.size() > 0){
                log.info("获取文章基本信息开始url:"+list.get(0).getUrl());
                toPython(articleUrl,list.get(0).getUrl());
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    //文字转语音
    public void TTS(){
        try {
            SysSpiderArticle article = new SysSpiderArticle();
            //文章下载完成
            article.setState("1");
            List<SysSpiderArticle> list = sysSpiderArticleService.selectSysSpiderArticleList(article);
            //
            if(list != null && list.size() > 0){
                SysSpiderArticleStepConrent conrent = new SysSpiderArticleStepConrent();
                //获取文章信息
                conrent.setArtcleId(list.get(0).getId());
                List<SysSpiderArticleStepConrent> conrentList = stepConrentService.selectSysSpiderArticleStepConrentList(conrent);
                for(SysSpiderArticleStepConrent stepConrent:conrentList){
                    log.info("文字转语音开始text:"+stepConrent.getContent());
                    String url = textToAudio(stepConrent.getContent(),stepConrent.getId());
                    //更新合成信息
                    SysSpiderArticleStepConrent content = new SysSpiderArticleStepConrent();
                    //获取文章信息
                    content.setId(stepConrent.getId());
                    content.setAudio(url);
                    content.setAudioState("1");
                    stepConrentService.updateSysSpiderArticleStepConrent(content);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    //语音转视频
    public void audioToVideo(){
        try {
            SysSpiderArticle article = new SysSpiderArticle();
            //文章下载完成
            article.setState("1");
            List<SysSpiderArticle> list = sysSpiderArticleService.selectSysSpiderArticleList(article);
            //调用python
            if(list != null && list.size() > 0){
                SysSpiderArticleStepConrent conrent = new SysSpiderArticleStepConrent();
                //获取文章信息
                conrent.setAudioState("1");
                conrent.setArtcleId(list.get(0).getId());
                List<SysSpiderArticleStepConrent> conrentList = stepConrentService.selectSysSpiderArticleStepConrentList(conrent);
                for(SysSpiderArticleStepConrent stepConrent:conrentList){
                    log.info("语音转视频开始text:"+stepConrent.getContent());
                    String name = save_path + stepConrent.getId()+".mp4";
                    // 调用合成脚本
                    audioToVideoPython(stepConrent.getId(),articleAudioToVideo,stepConrent.getAudio(),stepConrent.getImg());
                    //更新合成信息
                    SysSpiderArticleStepConrent content = new SysSpiderArticleStepConrent();
                    content.setId(stepConrent.getId());
                    content.setVideo(name);
                    content.setVideo("1");
                    stepConrentService.updateSysSpiderArticleStepConrent(content);
                }
                //查询视频是否合成完
                SysSpiderArticle sysSpiderArticle = new SysSpiderArticle();
                sysSpiderArticle.setId(list.get(0).getId());
                List<SysSpiderArticle> statelist = sysSpiderArticleService.selectSysSpiderArticleVideoState(sysSpiderArticle);
                if(statelist != null && statelist.size() > 0){
                    SysSpiderArticle spiderArticle = new SysSpiderArticle();
                    spiderArticle.setId(list.get(0).getId());
                    spiderArticle.setState("2");
                    sysSpiderArticleService.updateSysSpiderArticle(spiderArticle);
                }

            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    //视频合成
    public void videoMerge(){
        try {
            SysSpiderArticleUrl url = new SysSpiderArticleUrl();
            url.setState("0");
            List<SysSpiderArticleUrl> list = sysSpiderArticleUrlService.selectSysSpiderArticleUrlList(url);
            //调用python
            if(list != null && list.size() > 0){
                log.info("获取文章开始url:"+list.get(0).getUrl());
                toPython(articleInfoUrl,list.get(0).getUrl());
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }


    private void toPython(String pyUrl,String fileUrl){
        try {
            String py = "python3";
            String url = "/Users/yuzhicheng/project/python-video/spider/spider-wikiHow/ceshi.py";
            String id = UUID.randomUUID().toString();
            String file_url = "/Users/yuzhicheng/project/python-video";
            String[] args = new String[] { py, pyUrl, id, fileUrl };
            // 执行py文件
            Process proc = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void audioToVideoPython(String name,String pyUrl,String fileUrl,String imgUrl){
        try {
            String py = "python3";
            String url = "/Users/yuzhicheng/project/python-video/spider/spider-wikiHow/ceshi.py";
            String file_url = "/Users/yuzhicheng/project/python-video";
            String[] args = new String[] { py, pyUrl, name, fileUrl,imgUrl };
            // 执行py文件
            Process proc = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private String textToAudio(String text,String id){
        String save_url = save_path+ id;
        try {
            GlobalConfig.ifLog = true;
            //从配置文件读取密钥
            String appId = "1253542401";
            String secretId = "AKIDeBlFeuJ5cS8I8zQvz2wjruXkKLwkHDKI";
            String secretKey = "76vgL6n43dZJx6a2Mp7LTQAmiWbhet0x";


            //创建SpeechSynthesizerClient实例，目前是单例
            SpeechClient client = SpeechClient.newInstance(appId, secretId, secretKey);
            //初始化SpeechSynthesizerRequest，SpeechSynthesizerRequest包含请求参数
            SpeechSynthesisRequest request = SpeechSynthesisRequest.initialize();
            request.setCodec(codec);
            //request.setSampleRate(sampleRate);
            //request.setVolume(10);
            //request.setSpeed(2f);
            request.setVoiceType(type);
            //request.setPrimaryLanguage(2);
            //request.setSampleRate(null);
            //使用客户端client创建语音合成实例
            SpeechSynthesizer speechSynthesizer = client.newSpeechSynthesizer(request, new SpeechSynthesisListener(){

                @Override
                public void onComplete(SpeechSynthesisResponse response) {
//                Ttsutils.responsePcm2Wav(sampleRate, response.getAudio(), response.getSessionId());
                    Ttsutils.responsePcm2Wav(sampleRate, response.getAudio(), save_url);
                }

                @Override
                public void onMessage(byte[] data) {
                }

                @Override
                public void onFail(SpeechSynthesisResponse exception) {

                }
            });
            //执行语音合成
            speechSynthesizer.synthesisLongText(text);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return save_url;
    }






}
